<template>
  <div class="community-container">
    <el-card class="community-card">
      <template #header>
        <div class="card-header">
          <h2>社区讨论</h2>
          <el-input
            v-model="searchKeyword"
            placeholder="搜索帖子..."
            prefix-icon="el-icon-search"
            clearable
            class="search-input"
          />
        </div>
      </template>

      <div class="post-list">
        <el-empty v-if="filteredPosts.length === 0" description="暂无帖子" />
        
        <div v-else class="posts-grid">
          <el-card 
            v-for="post in filteredPosts" 
            :key="post.id" 
            class="post-item" 
            @click="openPostDetail(post.id)"
            tabindex="0"
            @keyup.enter="openPostDetail(post.id)"
            role="button"
            aria-label="帖子详情"
          >
            <div class="post-header">
              <h3 class="post-title" :title="post.title">{{ post.title }}</h3>
              <div class="time">{{ formatDate(post.created_at) }}</div>
            </div>
            
            <p class="author">作者：{{ post.user.username || '匿名' }}</p>
            <p class="summary">{{ post.content.slice(0, 100) }}{{ post.content.length > 100 ? '...' : '' }}</p>
            
            <div class="post-meta">
              <span>👍 {{ post.likes }}</span>
              <span>💬 {{ post.comments }}</span>
              <span>📅 {{ formatDate(post.created_at) }}</span>
            </div>
          </el-card>
        </div>
      </div>

      <!-- 创建帖子按钮 -->
      <button class="create-post-btn" @click="showCreateDialog = true" aria-label="新建帖子">+ 发帖</button>

      <!-- 创建帖子对话框 -->
      <el-dialog
        v-model="showCreateDialog"
        title="📝 新建帖子"
        width="600px"
        :close-on-click-modal="false"
        destroy-on-close
      >
        <div class="dialog-body">
          <el-form @submit.prevent="handleSubmit" autocomplete="off">
            <div class="form-group">
              <label for="input-title">标题：</label>
              <el-input
                id="input-title"
                v-model.trim="newPost.title"
                type="text"
                required
                placeholder="请输入标题（最多50字）"
                maxlength="50"
                class="input-title"
                autofocus
              />
              <div class="char-counter">{{ newPost.title.length }}/50</div>
            </div>

            <div class="form-group">
              <label for="input-content">内容：</label>
              <el-input
                id="input-content"
                v-model.trim="newPost.content"
                type="textarea"
                required
                placeholder="在这里写下你的想法..."
                rows="6"
                maxlength="1000"
                class="input-content"
              />
            </div>

            <div class="dialog-footer">
              <el-button @click="closeCreateDialog">取消</el-button>
              <el-button 
                type="primary" 
                @click="handleSubmit"
                :loading="isSubmitting"
                :disabled="!isFormValid"
              >
                {{ isSubmitting ? '发布中...' : '发布' }}
              </el-button>
            </div>
          </el-form>
        </div>
      </el-dialog>

      <!-- 分页 -->
      <div v-if="hasMore || currentPage > 1" class="pagination">
        <el-button :disabled="currentPage <= 1" @click="prevPage">上一页</el-button>
        <span>第 {{ currentPage }} 页</span>
        <el-button :disabled="!hasMore" @click="nextPage">加载更多</el-button>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { createPost, loadPosts } from '../services/commuServ'

// 状态管理
const searchKeyword = ref('')
const showCreateDialog = ref(false)
const isSubmitting = ref(false)
const currentPage = ref(1)
const hasMore = ref(true)
const posts = ref([])

const newPost = ref({
  title: '',
  content: ''
})

// 计算属性
const filteredPosts = computed(() => {
  if (!searchKeyword.value) return posts.value
  
  const keyword = searchKeyword.value.toLowerCase()
  return posts.value.filter(post => 
    post.title.toLowerCase().includes(keyword) ||
    post.content.toLowerCase().includes(keyword) ||
    post.user.username.toLowerCase().includes(keyword)
  )
})

const isFormValid = computed(() => {
  return newPost.value.title.trim() && newPost.value.content.trim()
})

// 方法
const formatDate = (dateString) => {
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

const loadMorePosts = async (page = 1, reset = false) => {
  try {
    const response = await loadPosts((page - 1) * 10, 10)
    if (reset) {
      posts.value = response.data
    } else {
      posts.value = [...posts.value, ...response.data]
    }
    hasMore.value = response.data.length === 10
  } catch (err) {
    ElMessage.error('加载帖子失败')
    console.error('Failed to load posts:', err)
  }
}

const prevPage = () => {
  if (currentPage.value > 1) {
    currentPage.value--
    loadMorePosts(currentPage.value, true)
  }
}

const nextPage = () => {
  if (hasMore.value) {
    currentPage.value++
    loadMorePosts(currentPage.value)
  }
}

const closeCreateDialog = () => {
  showCreateDialog.value = false
  newPost.value = { title: '', content: '' }
  isSubmitting.value = false
}

const handleSubmit = async () => {
  if (!isFormValid.value || isSubmitting.value) return
  
  try {
    isSubmitting.value = true
    const result = await createPost(newPost.value)
    posts.value.unshift(result)
    ElMessage.success('发布成功')
    closeCreateDialog()
  } catch (err) {
    ElMessage.error('发布失败: ' + (err?.response?.data?.message || '未知错误'))
  } finally {
    isSubmitting.value = false
  }
}

const openPostDetail = (postId) => {
  window.open(`/post/${postId}`, '_blank')
}

// 生命周期
onMounted(async () => {
  await loadMorePosts()
})
</script>

<style scoped>
.community-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.community-card {
  border-radius: 12px;
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h2 {
  margin: 0;
  font-size: 1.5rem;
  color: #303133;
}

.search-input {
  width: 300px;
}

.posts-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(380px, 1fr));
  gap: 16px;
  margin-top: 16px;
}

.post-item {
  cursor: pointer;
  transition: all 0.3s;
  border-radius: 8px;
}

.post-item:hover {
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.1);
  transform: translateY(-3px);
}

.post-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 12px;
}

.post-title {
  font-weight: 600;
  font-size: 16px;
  color: #303133;
  margin: 0;
  max-width: 70%;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.author {
  color: #606266;
  font-size: 14px;
  margin: 8px 0;
}

.summary {
  color: #666;
  margin: 8px 0;
  line-height: 1.5;
}

.post-meta {
  display: flex;
  gap: 16px;
  color: #909399;
  font-size: 14px;
}

.create-post-btn {
  position: fixed;
  bottom: 44px;
  right: 44px;
  background: #409EFF;
  color: #fff;
  border: none;
  width: 60px;
  height: 60px;
  border-radius: 50%;
  font-size: 2rem;
  cursor: pointer;
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.29);
  z-index: 70;
  transition: all 0.18s;
}

.create-post-btn:hover {
  background: #66b1ff;
  box-shadow: 0 6px 16px rgba(64, 158, 255, 0.38);
}

.dialog-body {
  padding: 20px;
}

.form-group {
  margin-bottom: 20px;
  position: relative;
}

.form-group label {
  display: block;
  margin-bottom: 8px;
  font-weight: 500;
  color: #606266;
}

.char-counter {
  position: absolute;
  right: 10px;
  top: 40px;
  color: #909399;
  font-size: 12px;
}

.dialog-footer {
  text-align: right;
  margin-top: 20px;
}

.pagination {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 20px;
  margin-top: 20px;
}

@media (max-width: 768px) {
  .posts-grid {
    grid-template-columns: 1fr;
  }
  
  .card-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
  
  .search-input {
    width: 100%;
  }
  
  .create-post-btn {
    bottom: 20px;
    right: 20px;
  }
}
</style>